/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.laamella.syntherface.synths.models;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 * 
 * @author danny
 */
public class StringModel {
	private int maxLength;
	public final PlainDocument document = new PlainDocument() {
		@Override public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
			if (maxLength > 0) {
				if (getLength()+str.length() > maxLength) {
					return;
					// hacky hacky
				}
			}
			super.insertString(offs, str, a);
		}
	};

	public StringModel() {
		this("");
	}

	public StringModel(String text) {
		this(text, -1);
	}

	public StringModel(int maxLength) {
		this("", maxLength);
	}

	public StringModel(String text, int maxLength) {
		this.maxLength=maxLength;
		setText(text);
	}

	public void setText(String newText) {
		try {
			document.replace(0, getLength(), newText, null);
		} catch (BadLocationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String getText() {
		try {
			return document.getText(0, getLength());
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
		return "";
	}

	public int getLength() {
		return document.getLength();
	}

	@Override public String toString() {
		return "StringModel: \"" + getText() + "\"";
	}
}
